import Home from "@/views/home.vue";
import Login from "@/views/login.vue";
import LinkView from "@/views/linkView.vue";

import {createRouter, createWebHashHistory} from "vue-router";
import store from "@/store/store.js";
import request from "@/util/request.js";
import {start, close} from "@/util/progress"

const views = import.meta.glob("./views/**/**.vue");
//上面这句会被vite编译成：
// const modules = {
//     './src/foo.js': __glob__0_0,
//     './src/bar.js': __glob__0_1
// }
const loadViewComponent = (viewPath) => {
    return views["./views/" + viewPath];
}
//系统关键功能的路由，记录在这里防止数据库中被清空
// let systemRoute = [{
//     label: '系统管理',
//     name: 'system',
//     path: '/system',
//     children: [{path: '/system/sysUser', component: () => import("@/views/system/sysUser/sysUser.vue")},//用户管理
//         {path: '/system/sysRole', component: () => import("@/views/system/sysRole/sysRole.vue")},//角色管理
//         {path: '/system/userRole', component: () => import("@/views/system/sysUser/userRole.vue")},//用户关联角色
//         {path: '/system/sysMenu', component: () => import("@/views/system/sysMenu/sysMenu.vue")},//菜单管理
//     ]
// }, {
//     name: '系统工具',
//     path: '/system-util',
//     children: [{path: '/system/codeGenerator', component: () => import("@/views/system/codeGenerator/index.vue")}],//代码生成功能]
// }]
const routes = [{
    path: '/',
    component: Home,
    name: 'home',
    children: [
        {path: '/index', component: () => import("@/views/index.vue"), name: '首页'},
        {path: '/me', component: () => import("@/views/system/personal/personal.vue"), name: '个人中心'},
    ]
}, {path: '/login', component: Login},]

const router = createRouter({
    // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
    history: createWebHashHistory(), routes, // short for `routes: routes`
})
const noShowedMenu = [
    {routePath: '/index', menuName: '首页', titles: ['首页']},
    {routePath: '/me', menuName: '个人中心', titles: ['个人中心']},
]

//从后端获得用户信息
function dealMenu(menuTree, fatherTitles = []) {
    for (let menu of menuTree) {
        menu.titles = [...fatherTitles, menu.menuName]
        menu.children = menu.children || []
        let children = menu.children;
        if (menu.menuType === 'page') {
            let routeObj = {
                path: menu.routePath,
                component: loadViewComponent(menu.viewFilePath), // component: () => import( './views/' + menu.viewFilePath),
            }
            router.addRoute("home", routeObj)
            menu.children = null
            children = []
        }
        if (menu.menuType === 'link') {
            let routeObj = {
                path: menu.routePath,
                component: LinkView, // component: () => import( './views/' + menu.viewFilePath),
            }
            router.addRoute("home", routeObj)
            menu.children = null
            children = []
        }
        dealMenu(children, menu.titles)
    }
}

function getMenuList(menuTree, menuList = []) {
    for (let menu of menuTree) {
        menu.children = menu.children || []
        let children = menu.children;
        if (menu.menuType === 'page' || menu.menuType === 'link') {
            menu.children = null
            children = []
            menuList.push(menu);
        }
        getMenuList(children, menuList)
    }
}

async function loadUserInfo() {
    if (store.state.user.userInfo === null) {
        //请求后台获得登录用户的信息，如果仍旧没有信息，就代表没登录
        let res;
        try {
            res = await request({
                method: 'post', url: '/api/login/getCurrentUser',
            })
            if (res.code === 200) {
                //调用本地login方法，记住用户的信息
                await store.dispatch('user/login', res.data)
                //添加路由
                dealMenu(res.data.menuTree)
                //合并左侧菜单中的和不在左侧菜单中的，比如个人中心、待办消息等页面，这俩页面只要用户登录就可以看到，不需要在菜单中配置
                let allMenuList = []
                getMenuList(res.data.menuTree, allMenuList)
                allMenuList = [...allMenuList, ...noShowedMenu]
                store.commit("user/setViewInfoList", allMenuList)
                //返回用户信息
                return res.data
            }
            //返回0代表加载用户信息失败
            return {userRes: 0}
        } catch (error) {
            //请求失败
            let status = error.request.status
            if (status === 401) {
                //当前用户未登录
                return {userRes: 0}
            }
        }
    } else {
        //返回1代表用户信息已经存在
        return {userRes: 1, userInfo: store.state.user.userInfo}
    }

}

router.beforeEach(async (to, from, next) => {
    //如果直接访问的登录页面，直接跳过去
    start()
    if (to.fullPath === '/login') {
        next()
    } else if (to.fullPath === '/') {
        next({path: "/index", replace: true})
    } else {
        //请求每个路由页面之前判断当前用户是否登录
        let {userRes, userInfo} = await loadUserInfo()
        if (userRes === 1) {
            // 1代表用户信息已经存在
            // 判断用户是否有菜单，如果没有就跳转到个人中心
            if (userInfo.menuTree && userInfo.menuTree.length > 0) {
                next();
            } else {
                //没有菜单，就跳转到个人中心
                if (to.fullPath !== '/me') {
                    console.log('用户没有任何菜单，跳转到个人中心')
                    next({path: "/me", replace: true});
                } else {
                    next();
                }
            }
        } else if (userRes === 0) {
            // 0代表用户信息加载失败
            next({path: "/login", replace: true});
            console.log("还未登录");
        } else {
            // 用户信息已经加载成功了
            // 因为菜单还没加载到router中，所以这里直接调用next()会找不到路由。
            // 等菜单数据全部加载完成
            next({...to, replace: true});
            // next()
        }
    }
})
router.afterEach(() => {
    close()
})
const NO_ROUTE_PATH = [
    "/login"
]
router.afterEach((to, from, next) => {
    if (NO_ROUTE_PATH.indexOf(to.fullPath) < 0) {
        //从用户菜单里找到菜单的信息
        const targetMenu = findMenu(store.state.user.viewInfoList, to.fullPath);
        //找到组件
        let allRoutes = router.getRoutes()
        let targetComponent = null
        for (let route of allRoutes) {
            if (route.path === to.path) {
                targetComponent = route.components.default
            }
        }
        if (targetMenu) {
            store.commit('tab/addTab', {
                path: targetMenu.routePath,
                title: targetMenu.menuName,
                component: targetComponent,
                menuType: targetMenu.menuType,
                linkUri: targetMenu.linkUri
            });
            store.commit('tab/setBreadTitles', targetMenu.titles);
        }
    } else {
        //进入了个人中心或登录页面，清掉tab的选中状态
        //清理掉tab的选中状态
        store.commit('tab/clearSelect');
    }
})

function findMenu(menuList, path) {
    for (const menu of menuList) {
        if (menu.routePath === path) {
            return menu;
        }
    }
    return null;
}

export default router;
